import { h, render } from 'vue'
import Message from './m-message.vue'

const defaultOptions = {
  type: 'info',
  duration: 3000,
  message: ''
}
const closeAll = function () {
  const messageList = document.getElementsByClassName('m-message')
  for (let i = 0; i < messageList.length; i++) {
    messageList[i].remove()
  }
}

const renderCom = (options = {}) => {
  closeAll()
  options = {
    ...defaultOptions,
    ...options
  }
  const divEl = document.createElement('div')
  divEl.className = `m-message m-message--${options.type}`
  // 设置弹框 top 值
  setTop(divEl)
  // 创建虚拟dom
  const vDom = h(Message, options)
  // 将虚拟DOM挂载到div上
  render(vDom, divEl)
  // 将div添加到body上
  document.body.appendChild(divEl)
  // 定时器移除元素
  setTimeout(() => {
    divEl.remove()
  }, options.duration)
}

function setTop(divEl) {
  const messageList = document.getElementsByClassName('m-message')
  const len = messageList.length
  if (len > 0) {
    // 获取最后一个message
    const lastMessageDom = messageList[len - 1]
    // offsetTop是只读属性，不能直接修改
    divEl.style.top =
      lastMessageDom.offsetTop + lastMessageDom.offsetHeight + 20 + 'px'
  }
}

const MMessage = (options) => {
  renderCom(options)
}
MMessage.success = (options) => {
  renderCom({
    type: 'success',
    ...getOptions(options)
  })
}
MMessage.error = (options) => {
  renderCom({
    type: 'error',
    ...getOptions(options)
  })
}
MMessage.warning = (options) => {
  renderCom({
    type: 'warning',
    ...getOptions(options)
  })
}
MMessage.info = (options) => {
  renderCom({
    type: 'info',
    ...getOptions(options)
  })
}
MMessage.closeAll = closeAll

const getOptions = function (options) {
  let obj = {}
  if (typeof options === 'object') {
    obj = {
      ...options
    }
  } else if (typeof options === 'string') {
    obj = {
      message: options
    }
  }
  return obj
}

export default MMessage
